/**
 *
 */
package cn.hg.jfsa.manage.controller.system;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.ext.interceptor.GET;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.ehcache.CacheInterceptor;
import com.jfinal.plugin.ehcache.CacheName;
import com.jfinal.plugin.ehcache.EvictInterceptor;

import cn.hg.base.jfinal.controller.BaseController;
import cn.hg.base.kit.StrExtKit;
import cn.hg.jfsa.core.JfsaThreadLocal;
import cn.hg.jfsa.manage.controller.system.validator.OrgValidator;
import cn.hg.jfsa.manage.service.JfsaOrgService;
import cn.hg.jfsa.manage.web.LayuiPage;
import cn.hg.jfsa.model.JfsaAdmin;
import cn.hg.jfsa.model.JfsaOrg;
import cn.hg.jfsa.model.JfsaOrgRole;

/**
 * @author Golly
 */
public class JfsaOrgController extends BaseController {

	/**
	 * 机构服务
	 */
	@Inject
	private JfsaOrgService orgService;

	/**
	 * 跳转到新增页面
	 */
	public void add () {
		Integer parentId = this.getParaToInt("parentId", 0);
		JfsaOrg parent = new JfsaOrg().setParentId(0).put("parent_name", "").setSortNum(0);

		if (parentId > 0) {
			parent = JfsaOrg.DAO.findById(parentId);
		}

		// 创建新记录
		this.setAttr("org", new JfsaOrg().setParentId(parentId).put("parent_name", parent.getName()));
	}

	/**
	 * Ajax方式执行分派权限操作
	 */
	@Before (POST.class)
	public void ajaxAssignRole () {
		JfsaOrgRole bean = this.getBean(JfsaOrgRole.class, "orgRole");

		if (null == bean.getId()) {
			bean.save();
		} else {

			if (StrKit.isBlank(bean.getRoleIds())) {
				bean.delete();
			} else {
				bean.update();
			}

		}

		this.renderAjaxSuccessed();
	}

	/**
	 * Ajax删除功能
	 */
	@Before (EvictInterceptor.class)
	@CacheName ("jfsaOrg")
	public void ajaxDel () {
		// 通过页面传入的ID查找到记录
		JfsaOrg bean = JfsaOrg.DAO.findById(this.getParaToInt("id"));

		// 记录不存在则报错
		if (null == bean) {
			this.renderAjaxFailed("1", "记录不存在！");
			return;
		}

		boolean successed = Db.tx(new IAtom() {

			@Override
			public boolean run () throws SQLException {
				JfsaOrgController.this.orgService.del(bean, true);
				// 更新父对象的子对象ID列表
				JfsaOrgController.this.orgService.updateOrgChildredIds(JfsaOrg.DAO.findById(bean.getParentId()));
				return true;
			}

		});

		// 返回Ajax成功
		if (successed) {
			this.renderAjaxSuccessed();
		} else {
			this.renderAjaxFailed("1", "操作失败！");
		}

	}

	/**
	 * Ajax方式取得机构角色
	 */
	public void ajaxGetOrgRole () {
		JfsaOrg bean = JfsaOrg.DAO.findById(this.getParaToInt("id"));

		if (bean == null) {
			this.render("../record_not_exist.html");
			return;
		}

		List<Record> roleList = Db.find(
			"SELECT r.id, r.`name`, r.remark, FIND_IN_SET(r.id, or1.role_ids) > 0 AS LAY_CHECKED FROM jfsa_role AS r LEFT JOIN jfsa_org_role AS or1 ON r.status='on' AND or1.org_id=?",
			bean.getId());
		this.renderJson(new LayuiPage(roleList));
	}

	/**
	 * Ajax方式获取机构树
	 */
	@Before (POST.class)
	public void ajaxGetOrgTree () {
		this.renderJson(this.orgService.getTree());
	}

	/**
	 * Ajax方式新建或更新记录
	 */
	@Before ({
		OrgValidator.class, EvictInterceptor.class
	})
	@CacheName ("jfsaOrg")
	public void ajaxSaveOrUpdate () {
		// 获取页面传入的Bean
		JfsaOrg bean = this.getBean(JfsaOrg.class, "org");

		if (bean.getParentId().equals(bean.getId())) {
			this.renderAjaxFailed("1", "上级机构不能是自己！");
			return;
		}

		JfsaAdmin currAdmin = JfsaThreadLocal.getAdmin();
		JfsaOrg parent = JfsaOrg.DAO.findById(bean.getParentId());
		// 这里引用事务处理是为了方便Ajax模式处理
		boolean successed = Db.tx(new IAtom() {

			@Override
			public boolean run () throws SQLException {

				if (null == bean.getId()) {
					// 初始化数据
					bean.setCreatedTime(new Date()).setCreatorId(currAdmin.getId())
						.setEditorId(currAdmin.getId()).setEditedTime(new Date())
						.setPathIds(parent == null ? ""
							: parent.getPathIds() + (parent.getPathIds().length() > 0 ? "," : "")
								+ parent.getId())
						.setLayerNum(null == parent ? 0 : parent.getLayerNum() + 1)
						.save();
				} else {
					// 更新记录
					bean.setEditorId(currAdmin.getId())
						.setEditedTime(new Date())
						.update();
				}

				// 更新父对象的子对象ID列表
				JfsaOrgController.this.orgService.updateOrgChildredIds(parent);
				return true;
			}

		});

		// 返回Ajax成功
		if (successed) {
			this.renderAjaxSuccessed();
		} else {
			this.renderAjaxFailed("1", "操作失败！");
		}

	}

	/**
	 * Ajax方式查询
	 */
	// @Before(CacheInterceptor.class)
	// @CacheName("jfsaOrg")
	public void ajaxSearch () {
		// 建立查询键值对
		Kv para = Kv.by("type", this.getPara("type"))
			.set("sortField", StrExtKit.humpToUnderline(this.getPara("sortField")))
			.set("sortType", this.getPara("sortType"));
		// 通过SQL模板引擎构建SQL及参数
		SqlPara sqlPara = Db.getSqlPara("system.findOrg", para);
		List<JfsaOrg> list = JfsaOrg.DAO.find(sqlPara);
		// 返回Ajax调用的Json结果
		this.renderJson(new LayuiPage(list));
	}

	/**
	 * 跳转到分派权限页面
	 */
	@Before (GET.class)
	public void assignRole () {
		JfsaOrg bean = JfsaOrg.DAO.findById(this.getParaToInt("id"));

		if (bean == null) {
			this.render("../record_not_exist.html");
			return;
		}

		JfsaOrgRole orgRole = JfsaOrgRole.DAO.findFirst("SELECT * FROM jfsa_org_role WHERE org_id=?", bean.getId());
		this.setAttr("orgRole", orgRole == null ? new JfsaOrgRole() : orgRole);
		this.setAttr("org", bean);
	}

	/**
	 * 跳转到编辑页面
	 */
	public void edit () {
		JfsaOrg bean = JfsaOrg.DAO.findById(this.getParaToInt("id"));
		JfsaOrg parent = JfsaOrg.DAO.findById(bean.getParentId());

		if (parent != null) {
			bean.put("parent_name", parent.getName());
		}

		// 查询目标记录
		this.setAttr("org", bean);
	}

	/**
	 * 跳转到列表页面
	 */
	@Before (CacheInterceptor.class)
	@CacheName ("jfsaOrg")
	@Override
	public void index () {}

	/**
	 * 跳转到查看页面
	 */
	@Before (CacheInterceptor.class)
	@CacheName ("jfsaOrg")
	public void view () {
		JfsaOrg bean = JfsaOrg.DAO.findById(this.getParaToInt("id"));

		if (bean == null) {
			this.render("../record_not_exist.html");
			return;
		}

		JfsaOrg parent = JfsaOrg.DAO.findById(bean.getParentId());

		if (parent != null) {
			bean.put("parent_name", parent.getName());
		}

		this.setAttr("org", bean);
	}

}
